<template>
	<delivery-finance-table
		v-if="isCommitApply"
		:applyId="applyId"
		:mode="mode"
		:currentAct="'供应商发起融资'"
		v-on:showShotPreview="showShotPreview"
	></delivery-finance-table>
	<accept-preview v-else-if="isShowAcceptPreview" :applyId="applyId"></accept-preview>
	<div v-else class="m-window" v-loading="loading" element-loading-text="数据加载中">
		<el-row class="applyShortPreview-col" type="flex">
			<el-col class="opts-col">
				<el-button type="primary" @click="confirmApply" style="width:120px;">确认</el-button>
			</el-col>
			<el-col :span="23" class="info-table-col">
				<span style="color:red;">温馨提示：1、融资日期只限工作日 2、申请当天不能作为融资开始日（即放款日） 3、{{tagContent}}</span>
				<el-form :v-model="applyShortPreviewForm" ref="applyShortPreviewForm">
					<el-form-item>
						<table class="emphasis-table">
							<tr>
								<th>供应商</th>
								<td>{{applyShortPreviewForm.custName}}</td>
							</tr>
							<tr>
								<th>
									<div>
										<span style="color:red">*</span>
										<span>实际控制人</span>
									</div>
								</th>
								<td>
									<el-input
										placeholder="请输入实际控制人"
										v-model="applyShortPreviewForm.realController"
										maxlength="10"
										show-word-limit
										clearable
									></el-input>
								</td>
							</tr>
							<tr>
								<th>收款账户户名</th>
								<td>{{familyName}}</td>
							</tr>
							<tr>
								<th>收款账户账号</th>
								<td>{{bankNo}}</td>
							</tr>
							<tr>
								<th>收款账户开户行</th>
								<td>{{bank}}</td>
							</tr>
							<tr>
								<th>微信</th>
								<td>{{applyShortPreviewForm.custSrmWechat}}</td>
							</tr>
							<tr>
								<th>邮箱</th>
								<td>{{applyShortPreviewForm.custSrmEmail}}</td>
							</tr>
							<tr>
								<th>可融金额（元）</th>
								<td>{{getFormatMoney}}</td>
							</tr>
							<tr>
								<th>融资产品</th>
								<td>{{mode=='order'?'金单宝':'金货宝'}}</td>
							</tr>
							<tr>
								<th>
									<div>
										<span style="color:red">*</span>
										<span>融资金额（元）</span>
									</div>
								</th>
								<td>
									<el-input
										v-model="applyShortPreviewForm.money"
										placeholder="输入金额"
										:readonly="moneyReaadOnly"
										@keyup.native="changeMoney"
										@blur="changeMoneyFormat"
									></el-input>
								</td>
							</tr>
							<tr>
								<th>融资金额大写</th>
								<td>{{captainMoney}}</td>
							</tr>
							<tr>
								<th>服务费率（含税）</th>
								<td>
									<span>{{rateTips}}</span>
									<el-popover placement="right" title="利率说明" width="280" trigger="hover">
										<div>
											<p style="padding:5px 0">融资方式：{{mode=='order'?'金单宝':'金货宝'}}</p>
											<p style="padding:5px 0">还款方式：预扣利息服务费,到期还本</p>
											<el-table :data="gridData" border size="small">
												<el-table-column width="139" property="date" label="融资天数"></el-table-column>
												<el-table-column property="rate" label="融资利率"></el-table-column>
											</el-table>
										</div>
										<span slot="reference">
											<i class="el-icon-info"></i>
										</span>
									</el-popover>
								</td>
							</tr>
							<!-- <tr>
								<th>
									<div>
										<span style="color:red">*</span>
										<span>融资开始日期</span>
									</div>
								</th>
								<td>
									<el-date-picker
										v-model="applyShortPreviewForm.applyDate"
										type="date"
										placeholder="选择日期"
										value-format="timestamp"
										:picker-options="pickerOptionsBegin"
										:readonly="moneyReaadOnly"
									></el-date-picker>
								</td>
							</tr>-->
							<tr>
								<th>
									<div>
										<span>融资期限</span>
									</div>
								</th>
								<td>
									<span>{{tagContent}}</span>
									<el-popover
										placement="top-start"
										title="说明"
										width="220"
										trigger="hover"
										:content="tagContent"
									>
										<span slot="reference">
											<i class="el-icon-info"></i>
										</span>
									</el-popover>
									<!-- <i class="el-icon-info"></i> -->
								</td>
							</tr>
						</table>
					</el-form-item>
				</el-form>
			</el-col>
		</el-row>
		<!-- 线下评审弹窗 -->
		<el-dialog
			title="申请人联系方式"
			:visible.sync="custInfModel"
			v-dialogDrag
			:close-on-click-modal="false"
		>
			<h1 style="color:#bf1d1d; margin-bottom: 8px;">提示：贵司累计融资金额超过300万，需要线下评审，请填写贵司申请人和申请人手机！</h1>
			<el-form label-width="100px" :model="custInfForm" :rules="custInfRules" ref="custInfForm">
				<el-row>
					<el-col :span="24">
						<el-form-item label="申请人" prop="custName">
							<el-input v-model="custInfForm.custName" placeholder="请输入申请人姓名"></el-input>
						</el-form-item>
					</el-col>
					<el-col :span="24">
						<el-form-item label="申请人手机" prop="custPhone">
							<el-input
								v-model="custInfForm.custPhone"
								placeholder="请输入申请人手机号码"
								@keyup.native="verifyRestrict"
								maxlength="11"
							></el-input>
						</el-form-item>
					</el-col>
				</el-row>
			</el-form>
			<span slot="footer" class="dialog-footer">
				<!-- 取消与关闭不需要弹窗 -->
				<el-button type="primary" @click="closeModel">取消</el-button>
				<el-button type="primary" @click="saveSuccess('custInfForm')">确认</el-button>
			</span>
		</el-dialog>
	</div>
</template>
<style lang="less" rel="stylesheet/less" scoped>
.applyShortPreview-col {
	flex-direction: column;
	.info-table-col {
		margin-top: 10px;
	}
	.emphasis-table {
		width: 100%;
		margin-top: 10px;
		.hit {
			color: #409eff !important;
		}
		.font-underline {
			text-decoration: underline;
		}
		tr {
			&:nth-child(even) th,
			&:nth-child(even) td {
				background: #f9fafa;
			}
			td,
			th {
				border: 1px solid #eee;
				padding: 0 10px;
				height: 35px;
				line-height: 35px;
				text-align: right;
				width: 50%;
			}
			th {
				&:first-child {
					width: 10%;
					text-align: center;
				}
				&:last-child {
					width: 90%;
				}
			}
			td {
				text-align: left;
				& /deep/ .el-input__inner {
					border: none !important;
					outline-style: none !important;
					height: 35px;
					line-height: 35px;
					margin-left: -10px;
				}
				& /deep/ .el-input__prefix {
					left: -5px;
					top: -2px;
				}
				& /deep/ .el-date-editor {
					width: 322px;
				}
			}
		}
	}
}
</style>
<script>
import DeliveryFinanceTable from "./deliveryFinanceTable.vue";
import { regainOriginalMoneyFormat, formatPrice, formatRate, getSpecifyDate, switchCaptainMoney, formatPriceEdit } from "@/util/format.js";
import EmphasisTable from "@/components/emphasisTable.vue";
import { mapState, mapActions } from "vuex";
import Msg from "@/public/message"
/**
 * @group financeManager
 * 金单宝/金货宝确认申请
*/
export default {
	name: "deliveryFinancePreview",
	props: {
		// 引用模块
		mode: {
			//order金单宝，delivery交货融
			type: String,
			required: true
		},
		//从我的申请列表跳转
		applyListApplyId: {
			// 申请Id
			type: String
		}
	},
	data () {
		return {
			loading: true,
			whitelist: [],
			blacklist: [],
			EndDate: '',
			bankNo: '',
			familyName: '',
			bank: '',
			captainMoney: '',
			applyId: "",
			custInfModel: false,
			moneyReaadOnly: false,
			EndDateReadOnly: true,
			custInf: this.$store.state.supplyChainFinance.custInf, //获取供应商信息
			isCommitApply: false,
			isShowAcceptPreview: false,
			applyShortPreviewForm: {
				money: null,
				applyDate: '',
				prepaybackDate: '',//this.getPaybackDate(25)
				realController: ''
			},
			availableAmount: 0,
			allRepayment: 0,
			customerRate: "",
			custInfForm: {
				custName: "",
				custPhone: ""
			},
			custInfRules: {
				custName: [
					{
						required: true,
						message: "请输入申请人姓名",
						trigger: "blur"
					},
					{
						min: 2,
						max: 10,
						message: "长度在 2 到 10 个字符",
						trigger: "blur"
					}
				],
				custPhone: [
					{
						required: true,
						message: "请输入申请人手机号码",
						trigger: "blur"
					},
					{
						validator: (rule, value, callback) => {
							let mobile = /^((13[0-9])|(14[5,7,9])|(15[0-3,5-9])|(17[0,3,5-8])|(18[0-9])|166|198|199|(147)){1}(\d){8}$/
							if (!mobile.test(value)) {
								callback(new Error('请输入正确的手机号码'))
							} else {
								callback()
							}
						},
						trigger: 'blur'
					}
				]
			}
		};
	},
	beforeMount () {
		let params = {
			supplierId: this.custInf.custId //客户id
		};
		this.getAvailableAmount(params);
	},
	created () {
		this.applyShortPreviewForm.custSrmEmail = this.custInf.mail
		this.applyShortPreviewForm.custSrmWechat = this.custInf.weChatNo
		this.applyShortPreviewForm.custName = this.custInf.custName
		this.applyId = this.applyListApplyId
		this.getEsignAccountByCustId()
		if (this.applyId) {
			//获取申请主表信息
			this.$http.getApplyInfo({
				id: this.applyId
			}).then(({ data }) => {
				if (data.code == 200 || data.code == 1) {
					let row = data.rows;
					let applyAmt = row.applyAmt ? row.applyAmt : 0
					this.applyShortPreviewForm.money = formatPrice(applyAmt)
					this.captainMoney = switchCaptainMoney(applyAmt)
					this.applyShortPreviewForm.prepaybackDate = new Date(row.prepaybackDate).getTime()
					this.applyShortPreviewForm.applyDate = new Date(row.applyDate).getTime()
					this.applyShortPreviewForm.custSrmEmail = row.custSrmEmail ? row.custSrmEmail : this.custInf.mail
					this.applyShortPreviewForm.custSrmWechat = row.custSrmWechat ? row.custSrmWechat : this.custInf.weChatNo
					this.applyShortPreviewForm.realController = row.realController
				} else {
					this.$alert("获取申请表信息失败", {
						confirmButtonText: "确定",
						customClass: "alertFailure"
					});
				}
			})
				.catch(errror => {
					this.$alert("查询主表信息失败，请检查网络", {
						confirmButtonText: "确定",
						customClass: "alertFailure"
					});
				});
		} else {
			this.applyShortPreviewForm.realController = this.$global.realController
		}
		// this.applyShortPreviewForm.prepaybackDate = this.getPaybackDate(25)
		// let dd = new Date(new Date().toLocaleDateString());
		//this.applyShortPreviewForm.applyDate = dd.setDate(dd.getDate() + 1);
	},
	methods: {
		...mapActions(["changeFromPage"]),
        /**
		 * @vuese
		 * 正则验证手机号
		*/
		verifyRestrict () {
			this.custInfForm.custPhone = this.custInfForm.custPhone.replace(/[^\d]/g, '')
		},
        /**
		 * @vuese
		 * 对输入申请融资金额格式化
		*/
		changeMoneyFormat () {
			if (this.applyShortPreviewForm.money) {
				this.applyShortPreviewForm.money = this.applyShortPreviewForm.money.replace(/\.+$/, '')
				const nums = this.applyShortPreviewForm.money.toString().split('.')
				if (nums.length == 1) {
					this.applyShortPreviewForm.money = this.applyShortPreviewForm.money + '.00'
				}
				else if (nums[1].length == 1) {
					this.applyShortPreviewForm.money = this.applyShortPreviewForm.money + '0'
				}
				this.changeMoney()
			}
		},
		/**
		 * @vuese
		 * 获取当前供应商电子签信息
		*/
		async getEsignAccountByCustId () {
			let custId = this.supplyChainFinance.custInf.custId + ""
			let that = this
			await this.$http.getEsignAccountByCustId({ custId: custId }).then(({ data }) => {
				setTimeout(() => {
					that.loading = false
				}, 500);
				if (data.code == 200 && data.rows) {
					that.bankNo = data.rows.bank_no
					var bankinfo = data.rows.sub_bank
					bankinfo = bankinfo.replace(data.rows.bank, '')
					bankinfo = data.rows.bank + bankinfo
					that.bank = bankinfo
					that.familyName = data.rows.name
				} else {
					this.$alert(`获取数据失败：${data.info}`, {
						confirmButtonText: "确定",
						customClass: "alertFailure"
					})
				}
			}).catch(error => {
				this.loading = false
				this.$alert('查询失败，请检查网络！', {
					confirmButtonText: "确定",
					customClass: "alertFailure"
				})
			})
		},
        /**
		 * @vuese
		 * 限制输入金额格式
		*/
		changeMoney () {
			this.applyShortPreviewForm.money = this.applyShortPreviewForm.money.replace(/[^(\d|.)]/g, "");//只允许输入数字        
			if (this.applyShortPreviewForm.money < 0.01) {
				this.captainMoney = ''
				return;
			}
			this.applyShortPreviewForm.money = this.applyShortPreviewForm.money.replace(/\.{2,}/g, "."); //只保留第一个. 清除多余的   
			this.applyShortPreviewForm.money = this.applyShortPreviewForm.money.replace(".", "$#$").replace(/\./g, "").replace("$#$", ".");
			this.applyShortPreviewForm.money = this.applyShortPreviewForm.money.replace(/^(\-)*(\d+)\.(\d\d).*$/, '$1$2.$3');//只能输入两个小数   
			this.applyShortPreviewForm.money = formatPriceEdit(this.applyShortPreviewForm.money.toString().replace(/[,]/g, ''))
			let money = regainOriginalMoneyFormat(this.applyShortPreviewForm.money)
			this.captainMoney = money ? switchCaptainMoney(money) : ''
		},
        /**
		 * @vuese
		 * 确认融资发起融资流程
		*/
		confirmApply () {
			// if (this.applyId) {
			// 	//提交界面点击返回，当该页面主表id存在，那么就不需要新增数据，直接跳转到提交申请页面
			// 	this.isCommitApply = true;
			// 	this.changeFromPage("deliveryFinancePreview");
			// 	return;
			// }
			let money = regainOriginalMoneyFormat(this.applyShortPreviewForm.money);
			if (!money) {
				this.$alert("请输入融资金额", {
					confirmButtonText: "确定",
					customClass: "alertPrompt"
				});
				return;
			} else if (money <= 0) {
				this.$alert("融资金额必须大于0元", {
					confirmButtonText: "确定",
					customClass: "alertPrompt"
				});
				return;
			} else if (money > this.availableAmount) {
				this.$alert("融资金额不能大于可融金额", {
					confirmButtonText: "确定",
					customClass: "alertPrompt"
				});
				return;
			} else if (!this.applyShortPreviewForm.realController) {
				this.$alert("实际控制人不能为空", {
					confirmButtonText: "确定",
					customClass: "alertPrompt"
				});
				return;
			}
			let params = {
				applyAmt: money, //申请融资金额
				finType: 3, //融资类别 3金货宝;2金单宝
				custId: this.custInf.custId, //客户id
				custName: this.custInf.custName, //客户名称
				availableAmt: this.availableAmount,  //可融金额
				realController: this.applyShortPreviewForm.realController //实际控制人
			};
			if (this.mode == 'delivery') {
				params.finType = 3
				this.saveApplyInf(params).then(data => {
					this.applyId = (data && data.id) ? data.id : '';
					this.isCommitApply = true;
					this.isShowAcceptPreview = false;
					this.changeFromPage("deliveryFinancePreview");
				}).catch(err => {
					Msg.showErrorMsg(err)
				})
			} else if (this.mode == 'order') {
				params.finType = 2
				this.saveOrderFin(params).then(data => {
					this.applyId = (data && data.id) ? data.id : '';
					this.isCommitApply = true;
					this.isShowAcceptPreview = false;
					this.changeFromPage("deliveryFinancePreview");
				}).catch(err => {
					Msg.showErrorMsg(err)
				})
			}
		},
        /**
		 * @vuese
		 * 获取金单宝或金货宝可融资金额
		*/
		getAvailableAmount (params) {
			let apiName = ''
			if (this.mode == 'order') {
				// 获取订单融资可融额度
				apiName = 'getOrderFinAmount'
			} else if (this.mode == 'delivery') {
				// 获取交货融资可融额度
				apiName = 'getDeliveryFinAmount'
			}
			this.$http[apiName](params)
				.then(response => {
					if (response.data.code == 1) {
						if (this.mode == 'order') {
							this.availableAmount = response.data.rows.sumBorrowBalance
								? response.data.rows.sumBorrowBalance
								: 0.0;
						} else if (this.mode == 'delivery') {
							this.availableAmount = response.data.rows
								? response.data.rows
								: 0.0;
						}
					} else {
						this.availableAmount = 0;
					}
				})
				.catch(errror => {
					this.$alert("查询可融金额失败，请检查网络！", {
						confirmButtonText: "确定",
						customClass: "alertFailure"
					});
				});
		},
        /**
		 * @vuese
		 * 返回到确认申请页
		*/
		showShotPreview (val) {
			this.isCommitApply = false;
			//this.moneyReaadOnly = true;
			this.applyId = val;
		},
        /**
		 * @vuese
		 * 确认保存金单宝融资申请信息
         * @arg 参数params为Obj；代表接口请求参数
		*/
		saveOrderFin (params) {
			params.id = this.applyId
			const gLoading = this.$loading({
				lock: true,
				text: '确认申请融资中，请稍等',
				spinner: 'el-icon-loading',
				background: 'rgba(255, 255, 255, .9)'
			})
			return new Promise((resolve, reject) => {
				this.$http.confirmOrderFinance(params).then(({ data }) => {
					if (data.code == 1 || data.code == 200) {
						gLoading.text = '确认成功，正在跳转中...'
						setTimeout(() => {
							resolve(data.rows)
							gLoading.close()
						}, 600)
					} else {
						gLoading.close()
						reject(data.info)
					}
				}).catch(err => {
					gLoading.close()
					reject('确认申请金单宝失败!')
				})
			})
		},
        /**
		 * @vuese
		 * 确认保存金货宝融资申请信息
         * @arg 参数params为Obj；代表接口请求参数
		*/
		saveApplyInf (params) {
			params.id = this.applyId
			const gLoading = this.$loading({
				lock: true,
				text: '确认申请融资中，请稍等',
				spinner: 'el-icon-loading',
				background: 'rgba(255, 255, 255, .9)'
			})
			return new Promise((resolve, reject) => {
				this.$http.confirmApplyDeliveryFin(params)
					.then(response => {
						if (response.data.code == 1) {
							gLoading.text = '确认成功，正在跳转中...'
							setTimeout(() => {
								resolve(response.data.rows)
								gLoading.close()
							}, 600)
						} else {
							gLoading.close()
							reject(response.data.info)
						}
					})
					.catch(errror => {
						gLoading.close()
						reject('确认申请金货宝失败!')
					});
			})
		},
        /**
		 * @vuese
		 * 关闭弹窗
		*/
		closeModel () {
			this.custInfModel = false;
		},
		/**
		 * @vuese
		 * 确认提交线下申请
         * @arg 参数formName为表单组件名称
		*/
		saveSuccess (formName) {
			this.$refs[formName].validate(valid => {
				let money = regainOriginalMoneyFormat(this.applyShortPreviewForm.money)
				let sumNum = parseFloat(this.allRepayment) + parseFloat(money)
				if (valid) {
					this.$confirm('是否确认提交？').then(() => {
						let params = {
							applyAmt: money, //申请融资金额
							finType: 0, //融资类别
							custId: this.custInf.custId, //客户id
							custName: this.custInf.custName, //客户名称
							applyDate: this.applyShortPreviewForm.applyDate,//融资开始日期
							prepaybackDate: this.applyShortPreviewForm.prepaybackDate,//融资开始日期
							custUser: this.custInfForm.custName, //供应商对接人姓名
							custPhone: this.custInfForm.custPhone, //供应商对接人电话
							availableAmt: this.availableAmount,  //可融金额
							totalFinAmount: sumNum  //累积融资金额
						};
						let that = this;
						that.saveApplyInf(params, function (data) {
							that.applyId = (data && data.id) ? data.id : '';
							that.custInfModel = false;
							that.isCommitApply = false;
							that.isAcceptPreview = true
							that.isShowAcceptPreview = true
							that.changeFromPage("applyShortPreview");
						});
					}).catch(() => { })
				} else {
					return false;
				}
			});
		}
	},
	computed: {
		...mapState(["supplierApplyList", "supplyChainFinance"]),
		// 融资期限说明
		tagContent () {
			if (this.mode == 'order') {
				return '融资期限最大为本次融资使用订单里物料最早约定交货日期计算到次月25号,若25号非工作日提前!'
			} else {
				return '融资期限最大为本次融资使用订单已交货里物料最早的入库日期计算到次月的25号,若25号非工作日提前！'
			}
		},
		// 利率说明
		rateTips () {
			if (this.mode == 'order') {
				return '0-30天,利率0.05%;30-60天,利率0.04%;60-90天,利率0.035%'
			} else {
				return '0-15天,利率0.04%;15-30天,利率0.035%;30天以上,利率0.03%'
			}
		},
		// pop内容
		gridData () {
			let tableData = []
			if (this.mode == 'order') {
				tableData = [
					{ rate: '0.05%/天', date: '0-30天' },
					{ rate: '0.04%/天', date: '30-60天' },
					{ rate: '0.035%/天', date: '60-90天' },
				]
			} else {
				tableData = [
					{ rate: '0.04%/天', date: '0-15天' },
					{ rate: '0.035%/天', date: '15-30天' },
					{ rate: '0.03%/天', date: '30天以上' },
				]
			}
			return tableData
		},
		// 格式化可融金额
		getFormatMoney () {
			return formatPrice(this.availableAmount);
		}
	},
	components: {
		EmphasisTable,
		DeliveryFinanceTable
	}
};
</script>